package com.yf.system.modules.sys.log.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yf.ability.system.shiro.dto.SysUserLoginDTO;
import com.yf.framework.api.ApiRest;
import com.yf.framework.api.dto.PagingReqDTO;
import com.yf.framework.aspect.log.LogDataSetter;
import com.yf.system.modules.sys.log.dto.request.SysLogReqDTO;
import com.yf.system.modules.sys.log.dto.response.SysLogRespDTO;
import com.yf.system.modules.sys.log.entity.SysLog;
import com.yf.system.modules.sys.log.mapper.SysLogMapper;
import com.yf.system.modules.sys.log.service.SysLogService;
import com.yf.system.modules.sys.user.service.SysUserService;
import com.yf.system.modules.sys.user.utils.UserUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 日志服务实现类
 * @author bool
 */
@Service
public class SysLogServiceImpl extends ServiceImpl<SysLogMapper, SysLog> implements SysLogService, LogDataSetter {


    @Autowired
    private SysUserService sysUserService;

    @Override
    public IPage<SysLogRespDTO> paging(PagingReqDTO<SysLogReqDTO> reqDTO) {
        //转换结果
        IPage<SysLogRespDTO> pageData = baseMapper.paging(reqDTO.toPage(), reqDTO.getParams());
        return pageData;
     }

    @Override
    public void saveLog(String logType, String uri, String title, String ip, String jsonData, Boolean success, String log, Object object) {


        // 从token中获得用户ID
        String userId = UserUtils.getUserId(false);


        // 用户登录类型的日志特殊处理
        if(StringUtils.isBlank(userId) && !StringUtils.isBlank(logType) && "login".equals(logType)){
            ApiRest<SysUserLoginDTO> rest =   JSON.parseObject(JSON.toJSONString(object), new TypeReference<ApiRest<SysUserLoginDTO>>(){});
            if(rest!=null && rest.getData()!=null){
                userId = rest.getData().getId();
            }
        }


        // final赋值
        final String uid = userId;

        new Thread(() -> {
            SysLog sysLog = new SysLog();
            sysLog.setLogType(logType);
            sysLog.setSuccess(success);
            sysLog.setLog(log);
            sysLog.setData(jsonData);
            sysLog.setUri(uri);
            sysLog.setIp(ip);
            sysLog.setTitle(title);
            sysLog.setUserId(uid);
            sysLog.setCreateTime(new Date());
            save(sysLog);
        }).run();
    }

    @Override
    public String getUserId(String token) {
        SysUserLoginDTO dto = sysUserService.token(token);

        if(dto!=null){
            return dto.getId();
        }

        return "";
    }
}
